<?php

class BolaoTournamentPeer extends BaseBolaoTournamentPeer
{
  static function organizeByYear($tournaments)
  {
    $result = array();
    foreach ($tournaments as $tournament)
    {
      $year = $tournament->getStartDate('Y');
      if (!array_key_exists($year, $result))
        $result[$year] = array();
      $result[$year][] = $tournament;
    }
    return $result;
  }

  static function retrieveByNameAndYear($name_slug, $year, $category_slug, $subcategory_slug)
  {
    // Retrieve category and subcategory
    $category = BolaoCategoryPeer::retrieveByNameSlug($category_slug);
    $subcategory = BolaoSubcategoryPeer::retrieveByNameSlug($subcategory_slug, $category);

    // Mount name search string
    $name = str_replace('-', '_', $name_slug);

    $criteria = new Criteria();
    $cron = $criteria->getNewCriterion(BolaoTournamentPeer::NAME, $name, Criteria::LIKE);
    $cron->addAnd($criteria->getNewCriterion(BolaoTournamentPeer::SUBCATEGORY_ID, $subcategory->getId()));
    $criteria->add($cron);
    $criteria->setIgnoreCase(true);

    $result = BolaoTournamentPeer::doSelect($criteria);
    
    // If more than one result, filter by year
    if (count($result) > 1)
    {
      foreach($result as $t)
      {
        if ($t->getStartDate('Y') == $year) return $t;
      }
      // If not tournament as found with specified year, return NULL
      return NULL;
    }
    else if (count($result) == 1)
      return $result[0];
    else
      return NULL;
  }
}
